package DataOperator;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class BookPackager extends BasePackager{
	static final String BookFilePath = "Out/Book";
	
	private DataOutputStream bookWriter = null;
	private int itemOffset = 0;
	private ByteBuffer intBuffer = ByteBuffer.allocate(4);
	
	@Override
	protected void Init(){
		try{
			bookWriter = new DataOutputStream(new FileOutputStream(BookFilePath));
		}
		catch(IOException e){
			e.printStackTrace();
		}
	}
	
	private void WriteInt(int i) throws IOException{
		intBuffer.clear();
		intBuffer.order(ByteOrder.LITTLE_ENDIAN);
		intBuffer.putInt(i);
		intBuffer.order(ByteOrder.BIG_ENDIAN);
		bookWriter.write(intBuffer.array());
	}
	
	@Override
	protected void BeforeBuild() throws IOException{
		super.BeforeBuild();
		WriteInt(builder.GetBuildSize());
		itemOffset = (builder.GetBuildSize() + 1) * 4;
	}
	
	@Override
	protected void AfterBuild(){
		super.AfterBuild();
	}

	@Override
	public void PrepareWord(String word, WordBuildInfo info) throws IOException{
		super.PrepareWord(word, info);
		info.length = 4 * 2 + info.data.content.length() * 2 + info.soundFileLength;
		WriteInt(itemOffset);
		itemOffset += info.length;
	}
	
	@Override
	public void BuildWord(String word, WordBuildInfo info) throws IOException {
		// TODO Auto-generated method stub
		WriteInt(info.data.content.length() * 2);
		WriteInt(info.soundFileLength);
		bookWriter.writeChars(info.data.content);
		if(info.soundFileLength <= 0){
			noSoundWords.add(info.word);
		}
		else{
			byte[] buffer = new byte[info.soundFileLength];
			try {
				FileInputStream data = new FileInputStream(info.soundFilePath);
				data.read(buffer);
				bookWriter.write(buffer);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
